package cn.zniot.so.application.util;

import cn.zniot.so.application.constant.Constants;

import org.apache.commons.configuration.Configuration;
import org.apache.commons.configuration.ConfigurationException;
import org.apache.commons.configuration.XMLConfiguration;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import java.io.File;
import java.io.InputStream;
import java.util.Properties;

/**
 * 加载属性文件
 */
public class DownloadFile {

	/**
	 * 配置文件可能存在的目录 相对于HomeDir的目录
	 */
    
	/**
	 * 加载属性文件
	 * 
	 * @param homeDir
	 */
	public static void init(String homeDir,String fileName) {
		homeDir = homeDir + "/conf";
		
		// 应用程序配置文件
		String appPropertiesFileUrl = null;
		
		/*
		 * 先找到配置文件的fileurl
		 */
		if (appPropertiesFileUrl == null) {
			appPropertiesFileUrl = getFileUrl(homeDir,fileName);
			if (!isPropertiesFileExists(appPropertiesFileUrl)) {
				appPropertiesFileUrl = null;
			}
		}
		Log logger = LogFactory.getLog(DownloadFile.class);
		if (appPropertiesFileUrl != null) {
			try {
				Configuration config = new XMLConfiguration(
						appPropertiesFileUrl);
				Constants.initProperties(config);
			} catch (ConfigurationException e) {
				logger.error("加载zniot配置文件[" + appPropertiesFileUrl+ "]异常::", e);
			}
		} else {
			System.err.println(" --------------------------------------------------------- ");
			System.err.println(" --- Try to find the properties file of Application Failed...");
			System.err.println(" --- Please check whether your properties file of Application in your "
							+ homeDir
							+ " or "
							+ homeDir
							+ "/properties or "
							+ homeDir + "/prop directory exist.");
			System.err.println(" ---### Application will exit now! ###--- ");
			System.err.println(" ---###  Startup Failed!   System exit...###---");
			System.err.println(" --------------------------------------------------------- ");
			System.exit(0);
		}
	}

	
	/**
	 * 获取文件路径
	 * 
	 * @param path
	 * @param name
	 * @return
	 */
	private static String getFileUrl(String path, String name) {
		return path + "/" + name;
	}

	/**
	 * 检查文件是否存在
	 * 
	 * @param fileUrl
	 * @return
	 */
	private static boolean isPropertiesFileExists(String fileUrl) {
		File file = new File(fileUrl);
		return file.isFile();
	}
     
}
